<template>
  <div class="flex items-center justify-center h-screen bg-black" v-if="feedDetail">
    <!-- 防止高度与上面重合 -->
    <div @click="handlePlay">
      <nut-video
        ref="videoRef"
        :source="videoState.source"
        :options="videoState.options"
        @time="handleTimeChange"
        @play="onPlay"
        @pause="onPause"
      />
    </div>

    <!-- 暂停按钮 -->
    <div class="absolute w-full text-center" v-if="!playing" @click="handlePlay">
      <PlayStart color="#fff" width="2rem" height="2rem" />
    </div>

    <div class="absolute bottom-0 p-3 mb-2 w-full text-white">
      <!-- 标题 -->
      <div class="font-bold mb-2 text-lg">{{ feedDetail.feedTitle }}</div>
      <nut-ellipsis class="text-base mb-3" direction="end" expandText="展开" collapseText="收起" rows="2" :content="feedDetail.feedContent" />
      <!-- 视频进度条 -->
      <nut-progress :percentage="schedule" :show-text="false" size="small" stroke-color="rgba(0,0,0,0.5)" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { PlayStart } from "@nutui/icons-vue";
import * as FeedApi from "@/api/official-website/unit-feed";
import { useRoute } from "vue-router";
import { isIOS } from "@/utils/mini-program";

const route = useRoute();

// 获取信息流详情
const feedDetail = ref<FeedApi.FeedDetail | null>(null);
const videoState = computed(() => ({
  source: {
    src: feedDetail.value?.videoUrl,
    type: "video/mp4",
  },
  options: {
    // 隐藏操作栏
    controls: false,
    // 自动播放
    autoplay: !isIOS(),
    muted: false,
    playsinline: true,
    loop: true,
  },
}));
const getFeedDetail = async () => {
  const id = String(route.query.id);
  const res = await FeedApi.getFeedById(id);
  feedDetail.value = res.data;
};
getFeedDetail();

/** 视频播放器实例 */
const videoRef = ref<HTMLVideoElement | null>(null);

/** 播放器状态 */
const playing = ref(false);
const onPlay = () => (playing.value = true);
const onPause = () => (playing.value = false);
const handlePlay = () => (playing.value ? videoRef.value?.pause() : videoRef.value?.play());

// 监听视频播放进度
const schedule = ref(0);
const handleTimeChange = (current: string, time: string) => {
  schedule.value = (convertSecond(current) / convertSecond(time)) * 100;
};

// 将分钟转化成秒
const convertSecond = (time: string) => {
  const [min, second] = time.split(":");
  return +min * 60 + +second;
};
</script>

<style>
:root {
  --nut-progress-small-height: 2px;
  --nut-ellipsis-expand-collapse-color: #fff;
}
.nut-ellipsis__text {
  font-weight: bold;
}
</style>
